package com.aisile.wemedia.gateway.filters;


import com.aisile.wemedia.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Auther:yry
 * @Date:2023/12/26 0026
 * @VERSON:1.0
 */
@Component  // java Config类
public class AuthorizFilter implements GlobalFilter, Ordered {


    /**
     *
     * @param exchange 请求和响应的上下文对象
     * @param chain gateway 的 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.  确定登录路径
        ServerHttpRequest request =  exchange.getRequest();
        ServerHttpResponse response =  exchange.getResponse();
        try {
            //   /admin /api/v1/login/in    /admin /api/v1 /adchannel/list
            System.out.println(request.getURI().getPath());
            // 2.  放行路径
            if(request.getURI().getPath().contains("/login/in")){
                return chain.filter(exchange);
            }
            // 3. 获取前端传递的token  和前端 提前约定好  header方式传输  queryParam方式  cookie方式传输
            String token =  request.getHeaders().getFirst("token");
            if(token == null || "".equals(token.trim())){
                // 获取请求参数
                token = request.getQueryParams().getFirst("token");
                if(token == null || "".equals(token.trim())){
                    token = request.getCookies().getFirst("token").getValue();
                }
            }
            // token  3.1 token 不能为空
            if(token == null || "".equals(token.trim())){
                // 拦截  返回http的状态码  200 400 404 500 503 401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            // 3.2 token 有效？
            Claims claims =  AppJwtUtil.getClaimsBody(token);
            // 3.3 是否过期
            int i =  AppJwtUtil.verifyToken(claims);
            if(i>0 || i<-1){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            // 都没问题  转发到路由地址就行
            request.mutate().header("token",token);
            return chain.filter(exchange);
        }catch (Exception e){
            // 需要认证
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    // 数越小  优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
